package com.mesd.killer.importer;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;

public class CupGameResultManager extends GameResultManager
{
	public static final String LEAGUE_NAME = "日联杯";

	public static final String NEW_SEASON = "2012-2013";

	public HashMap<Integer, String> teamMap = new HashMap();

	public static final HashMap leagueIdList = new HashMap();

	public static void main(String[] args)
		throws Exception
	{

		CupGameResultManager manager = new CupGameResultManager();
//		 manager.parseURL("http://info.bet007.com/jsData/matchResult/2012/c72.js");
//		 manager.parseURL("http://info.bet007.com/jsData/matchResult/2011/c72.js");
//		 manager.parseURL("http://info.bet007.com/jsData/matchResult/2010/c72.js");
//		 manager.parseURL("http://info.bet007.com/jsData/matchResult/2009/c72.js");

		manager.importNewLeagueSaichen();
	}

	static
	{
		leagueIdList.put(
			103, "欧冠");
		leagueIdList.put(
			113, "欧罗巴");
	}

	public int getLeagueID(String leagueName)
	{
		int ID = 0;
		Set keys = leagueIdList.keySet();
		for (Iterator<Integer> iterator = keys.iterator(); iterator.hasNext();)
		{
			int key = iterator.next();
			if (leagueName.equalsIgnoreCase((String) leagueIdList.get(key)))
			{
				return key;
			}
		}
		return ID;
	}

	public void insertLeagueTeam(String leagueName, String line, Connection conn)
	{
		try
		{
			// Statement stmt = conn.createStatement();
			int leagueID = getLeagueID(leagueName);
			String[] arrTeams = line.split("=");
			String teams = arrTeams[1];
			String[] arrTeams1 = teams.split("\\]\\,\\[");
			String[] s = arrTeams1[0].split(",");
			int teamID = Integer.parseInt(s[0].substring(3));
			String teamName = s[1].replaceAll(
				"'", "").trim();
			teamMap.put(
				teamID, teamName);
			// String sql = "insert into league_team values(" + leagueID + ",'"
			// + LEAGUE_NAME + "',"
			// + teamID + ",'" + teamName + "')";
			// stmt.addBatch(sql);
			for (int i = 1; i < arrTeams1.length; i++)
			{
				s = arrTeams1[i].split(",");
				teamID = Integer.parseInt(s[0]);
				teamName = s[1].replaceAll(
					"'", "").trim();
				teamMap.put(
					teamID, teamName);
				// sql = "insert into league_team values(" + leagueID + ",'" +
				// LEAGUE_NAME + "',"
				// + teamID + ",'" + teamName + "')";
				// stmt.addBatch(sql);
			}
			// stmt.executeBatch();
			// stmt.close();
		}
		catch (Exception e)
		{
			// e.printStackTrace();
		}
	}

	public boolean isNumeric(String str)
	{
		for (int i = str.length(); --i >= 0;)
		{
			if (!Character.isDigit(str.charAt(i)))
			{
				return false;
			}
		}
		return true;
	}

	@Override
	public void parseURL(String leagueName, String urlString)
	{
		Connection conn = DBUtil.getConnection();
		Statement stmt  = null;
		try
		{
			URL url = new URL(urlString);
			InputStream inputStream = (InputStream) url.getContent();
			BufferedReader da = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			String line = da.readLine();
			System.out.println(line);
			stmt = conn.createStatement();
			while (line != null)
			{
				line = da.readLine();
				if (line != null && line.startsWith("var arrTeam"))
				{
					insertLeagueTeam(
						leagueName,line, conn);
					break;
				}
			}
			da.close();
			inputStream.close();
			inputStream = (InputStream) url.getContent();
			da = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			do
			{
				line = da.readLine();
				System.out.println(line);

				if (line.startsWith("jh"))
				{
					if (line.length() < 20)
					{
						continue;
					}
					String[] ss = line.split("= \\[\\[");
					String[] sss = ss[0].split("G");
					try
					{
						String round = sss[1].replaceAll(
							"\"]", "").trim();
						if (!isNumeric(round))
						{
							round = round.substring(
								0, round.length() - 1);
						}
						String[] ssss = ss[1].split("\\]\\,\\[");
						for (int j = 0; j < ssss.length; j++)
						{
							long gameID = 0;
							String[] so = ssss[j].split(",");
							gameID = Long.parseLong(so[0]);
							if (gameID < 100)
								continue;
							int state = Integer.parseInt(so[2]);
							String gameTime = so[3];
							String hostTeam = teamMap.get(Integer.parseInt(so[4]));
							String visitTeam = teamMap.get(Integer.parseInt(so[5]));
							String fullScore = so[6];
							String halfScore = so[7];
							String sql = "insert into game_result (game_id, game_time, league_name, host_team, visit_team, half_score, full_score, round, state)"
								+ " values("
								+ gameID
								+ ",convert(datetime,"
								+ gameTime
								+ "),'"
								+ leagueName
								+ "','"
								+ hostTeam
								+ "','"
								+ visitTeam
								+ "',"
								+ halfScore
								+ "," + fullScore + ",'" + round + "'," + state + ")";
							stmt.addBatch(sql);
						}

					}
					catch (Exception ex)
					{

					}

				}
			}
			while (line != null && !line.startsWith("var lastUpdateTime"));
			stmt.executeBatch();
			da.close();
		}
		catch(Exception ex)
		{
			
		}
		DBUtil.close(conn, stmt);
	}

	public String readSaichen(int ID, String season, String groupId)
		throws Exception
	{
		String u = "http://bf.bet007.com/Phone/cupsaicheng.aspx?" + "id=" + ID + "&season="
			+ season + "&groupid=" + groupId;
		URL url = new URL(u);
		URLConnection urlConn = url.openConnection();
		urlConn.connect();
		BufferedReader da = new BufferedReader(new InputStreamReader(urlConn.getInputStream(),
			"UTF-8"));
		String line = da.readLine();
		da.close();
		return line;
	}

	@Override
	public void importNewLeagueSaichen()
	{
		Properties props = new Properties();
		try
		{
			String name = "newCupSaichen.properties";
			InputStream in = new FileInputStream((CupGameResultManager.class.getResource("")+name).substring(6));
			props.load(in);
			Enumeration en = props.propertyNames();
			while (en.hasMoreElements())
			{
				String leagueName = (String) en.nextElement();
				String urlString = props.getProperty(leagueName);
				parseURL(
					leagueName, urlString);
			}
			in.close();
			updateGameResultBySB();
			updateGameResultByBet365();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
